package br.com.persist.core;

import java.util.Iterator;

import br.com.persist.api.PersistentContext;
import br.com.persist.api.RuntimeExecutionException;
import br.com.persist.api.VolatileContext;

public class FunctionPersistResource extends PersistResource {

	private Function function;

	public FunctionPersistResource(Function function) {
		super();
		this.function = function;
	}

	protected Object runWithParameters(VolatileContext volatileContext, PersistentContext persistentContext, Object... parameters)
			throws RuntimeExecutionException {
		if (function.getParameterNames().size() != parameters.length) {
			throw new RuntimeExecutionException("Expected " + function.getParameterNames().size() + " but found " + parameters.length);
		}

		Iterator<String> i = function.getParameterNames().iterator();
		for (Object value : parameters) {
			volatileContext.update(i.next(), value);
		}

		return function.execute(volatileContext, persistentContext);
	}

	@Override
	protected Object run(VolatileContext volatileContext, PersistentContext persistentContext) throws RuntimeExecutionException {
		return runWithParameters(volatileContext, persistentContext, new Object[0]);
	}
}
